from datetime import datetime
from core.celery import celery_app, TaskMonitor
from app.celery_task.models.celery_task import CeleryTask
from common.database import SessionLocal

from core.logger import logger, celery_task_id


@celery_app.task(bind=True)
def watch_dog(self):
    """
    celery异步任务的监控
    """
    celery_task_id.set(str(self.request.id))
    session = SessionLocal()
    task_name = self.name.split(".")[-1]

    object = CeleryTask.get_object_by_name(session, task_name)
    if not object:
        # 如果不存在，则添加
        task_id = self.request.id
        type = self.name.split(".")[1]
        comment = f"{task_name} begin"
        task_data = {
            "name": task_name,
            "type": type,
            "tid": task_id,
            "relation_uuid": 0,
            "state": "SUCCESS",
            "progress": 100,
            "start_at": datetime.now(),
            "comment": comment
        }
        result = CeleryTask.add(session, task_data)
        if not result:
            logger.error(f"task_name:{task_name} task_id:{task_id}, add task failed")
            return False

        logger.info(f"task_name:{task_name} task_id:{task_id}, add task success")
    else:
        # 如果存在，则更新
        CeleryTask.update_task(session, object.tid)
        logger.info(f"{task_name} task_id:{object.tid}, update success")

    return True

if __name__ == '__main__':
    pass
